//删除的id
var delId = [];
//	时间初试化
$('#startTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#endTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});

$('#storageDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});

/*$('#storageDate').datetimepicker({
	// minView: "month",  //选择日期后，不会再跳转去选择时分秒 
	language:  'zh-CN',
	dateFormat: 'yyyy-mm-dd',//日期显示格式
	timeFormat:'HH:mm:ss',//时间显示格式
   	initialDate:new Date(),
	todayBtn:  1,
	autoclose: 1,
	minView:0,  //0表示可以选择小时、分钟   1只可以选择小时
	minuteStep:1,//分钟间隔1分钟
});*/

var oprateUrl = DOMAIN + '/v1/storage' + isLogin;
function loadTable() {
	$("#table").bootstrapTable({ // 对应table标签的id
		url: oprateUrl,
		method: 'get',
		cache: false,
		striped: true,
		pagination: true,
		pageSize: 50,
		pageNumber: 1,
		pageList: [50, 100],
		search: false,
		showColumns: false,
		clickToSelect: true,
		queryParams: {
			deleteFlg: 0
		},
		smartDisplay: false,
		columns: [/*{
			checkbox: true
		},*/ {
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}, {
			field: "storageNo",
			title: "入库单号",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "refundCode",
			title: "来源单号",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "storageDate",
			title: "入库时间",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "customerName",
			title: "货物来源",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "createUser",
			title: "创建人",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "createTime",
			title: "创建时间",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "storageType",
			title: "入库类型",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function (value, row, index) {
				if (row.deleteFlg == 1) {
					return '<button storageNo="' + row.storageNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">编辑</button>';
				} else {
					return '<button storageNo="' + row.storageNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">&emsp;查看</button>';
					/*<button data-del="' + oprateUrl + '" class="btn btn-primary btn-sm del">&emsp;删除</button>*/
				}
			}
		}],
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		showExport: true,
		//是否显示导出按钮
		buttonsAlign: "left",
		//按钮位置
		exportDataType: 'all',
		//导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		Icons: 'glyphicon glyphicon-export',
		exportTypes: ['excel', 'doc', 'xlsx', 'txt',],
		//导出文件类型
		exportOptions: {
			ignoreColumn: [0, 0],  //忽略某一列的索引，id删除更新用用，不显示与导出

			fileName: '导出数据表',
			//文件名称设置
			worksheetName: 'sheet1',
			//表格工作区名称
			tableName: '导出数据表',
			// excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式

		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
		formatNoMatches: function () {
			return '没有找到匹配的记录';
		}
	});
	function queryParams(params) {
		var params = {};
		return params;
	};
}

//查询
$("#selectPurchaseBtn").click(function () {
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		//params.customerName = $("#customerName").val();
		//params.statuses = $("#status option:checked").val();
		return params;
	};
	var url = DOMAIN + '/v1/storage' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

$("#tableAddDetail").bootstrapTable({ // 对应table标签的id
	//url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 200,
	ajaxOptions: {
	               async: false // 如果设置为异步，需要等请求成功后才会生成下面的tr和td，就无法在td中添加按钮
	           },
	pageNumber: 1,
	pageList: [200, 500],
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productName",
		title: "产品名称",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "productCode",
		title: "产品代码",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productType",
		title: "产品类别",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "grade",
		title: "产品级别",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "units",
		title: "单位",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "refundAmount",
		title: "订单数量",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "storageAmount",
		title: "入库数量",
		align: "center",
		valign: "middle",
		sortable: "true",
		formatter: function (value, row, index) {
			if(isEmpty(row.storageAmount)){
				row.storageAmount = row.refundAmount;
			}
			return row.storageAmount;
		},
		cellStyle:function(value,row,index){
			return {css:{"color":"#0088cc"}} 
		}
	},{
		field: "price",
		title: "单价",
		align: "center",
		valign: "middle"
	}, {
		field: "money",
		title: "行金额",
		align: "center",
		valign: "middle" 
	}],
	formatNoMatches: function () {
		return '';
	},
	onClickCell: function(field, value, row, $element) {
		if(field=="storageAmount"){
    		$element.attr('contenteditable', true);
       		$element.blur(function() {
       			if($element.html()=="" || isNaN($element.html())){
       					$element.html(value);
       			}else{
       				let index = $element.parent().data('index');
            		let tdValue = $element.html();
            		saveData(index, field, tdValue,row);
       			}
       		});
    	}
	}
});


 function saveData(index, field, value,row) {
        $("#tableAddDetail").bootstrapTable('updateCell', {
            index: index,       
            field: field,       //列名
            value: value        //cell值
        });
        $("#tableAddDetail").bootstrapTable('updateCell', {
		     index: index,       
		     field: 'money',       //列名
		     value: (row.storageAmount*row.price).toFixed(2)        //cell值
		 });
		 var rows = $('#tableAddDetail').bootstrapTable('getData');
		 	var allmoney = 0;
		 				for (var i = 0;i<rows.length;i++) {
		 					var money = parseFloat(rows[i].money);
		 					allmoney += money; 
		 				}
		 	allmoney = allmoney.toFixed(2);
		 	var allmoneystr = allmoney.toString();
		 /* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
		     document.getElementById("moneynum").innerHTML=allmoneystr;
}
function queryParams(params) {
	return params;
};

//新增按钮，不存到数据库
$("#AddPur-insertBtn").click(function () {
	//获取数据
	var productCode = $('#productCode').val();
	var productName = $('#productName').val();
	//判断商品是否已在明细中
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	for (var i = 0; i < rows.length; i++) {
		if (rows[i].productCode == productCode) {
			alert("商品" + productName + "已经存在，请输入其他商品");
			return;
		}
	}
	var productType = $('#productType').val();
	var grade = $('#grade').val();
	var units = $('#units').val();
	var amount = $('#amount').val();
	var price = $('#price').val();
	var money = $('#money').val();
	
	var count = $('#tableAddDetail').bootstrapTable('getData').length;
	var options = $("#tableAddDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	//var t = $('#info').serializeArray();
	var t = getFormJsonObject($("#info"));
	var flag = false;
	var flag = isInfoNull(t);
	if (!flag) {
		return;
	}
	$('#tableAddDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			pid: pid,
			productName: productName,
			productCode: productCode,
			productType: productType,
			grade: grade,
			units: units,
			price: price,
			amount:0,
			storageAmount: amount,
			money:money
		}
	});
	//新增后置空
	//$('#info')[0].reset();	
});

 //保存
$("#AddPur-saveBtn").click(function () {
	//得到新增表格数据
	var params = getDataForAdd();
	var flag = false;
	var flag = isMainNull(params);
	if (!flag) {
		alert("请先选择采购订单!");
		return;
	}
	params = JSON.stringify(params);
	console.log(params);
	//进货id是否绑定,没有id就新增
		//添加
		$.ajax({
			type: "post",
			url: DOMAIN + '/v1/storage'+ isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('保存失败');
			},
			complete: function () {
			}
		});
		//$('#info')[0].reset();
		$('#mainId').val('');
		$('.close').click();
		//将删除的id置空
		delId = [];
}); 

//新增时获取数据的方法
function getDataForAdd() {
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var params = {};
	params.storageDate = $("#storageDate").val();
	params.storageType = $("#storageType").val();
	params.purchaseCode = $("#purchaseCode").val();
	params.refundCode = $("#refundCode").val();
	params.refundStorageList = rows;
	return params;

}

//删除选中行
$("#AddPur-deleteBtn").click(function () {
	var ids = $("#tableAddDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'id', values: [id] });
				delId.push(id);
				}

		}

	}
});


 function isMainNull(t) {
 	if($('#purchaseCode').val()=='' || $('#purchaseCode').val()==null){
 		return false;
 	}
	return true;
	
} 
function isInfoNull(t) {

	if (t.productName == '' || t.productName == null) {
		alert("产品名称不能为空");
		return false;
	}
	if (t.price == '' || t.price < 0) {
		alert("商品单价必须大于零");
		return false;
	}
	return true;
}


//新增前填写日期并获取批次号与进货编号
function resetTable() {
	//$('#info').css("display","block");
	$("#info-btn").css("display","block");
	$("#storageType").removeAttr("disabled");
	//将删除的id置空
	 delId = [];
	 $('#main1')[0].reset();
	 //$('#info')[0].reset();
	time_rota($("#storageDate"));
	$("#refundOption").css("display","none");
	$("#purOption").css("display","block");
	$("#stor_customer").html("供应商");
	$('#tableAddDetail').bootstrapTable('removeAll');
	var allmoney = 0.0;
	allmoney = allmoney.toFixed(2);
	document.getElementById("moneynum").innerHTML=allmoney;
}

function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function (n, i) {
		indexed_array[n['name']] = n['value'];
	});

	return indexed_array;
};

//计算行金额
function calc(){
		var r_price = $("#price").val();
		var r_amount = $("#amount").val();
		if(r_price != "" && r_price >0 && r_amount >0 && r_amount != ""){
			$("#money").val((r_price*r_amount).toFixed(2));
		}else{
			$("#money").val(0);
		}
	}

//下拉框填充
$(function () {
	
	loadTable();
	
	 time_rota2($("#startTime"));
	 time_rota($("#endTime"));
	
	$("#storageType").on("change",function(){
		$("#purchaseCode").val("");
		$("#refundCode").val("");
		$("#customerName").val("");
		$('#tableAddDetail').bootstrapTable('removeAll');
		
		var storage_type = $("#storageType option:checked").html();
		if(storage_type=="采购入库"){
			$("#refundOption").css("display","none");
			$("#purOption").css("display","block");
			$("#stor_customer").html("供应商");
		}else{
			$("#refundOption").css("display","block");
			$("#purOption").css("display","none");
			$("#stor_customer").html("退货客户");	
		}
	});
	
	$("#price").on("blur",function(){
		calc();
	});
	
	$("#amount").on("blur",function(){
		calc();
	});
	
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		//params.customerName = $("#customerName").val();
		//params.statuses = $("#status option:checked").val();
		return params;
	};
	var url = DOMAIN + '/v1/storage' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

//查看信息
function EditInfo(e) {
	$('#tableAddDetail').bootstrapTable('removeAll');
	//$('#info').css("display","none");
	$("#info-btn").css("display","none");
	$("#storageType").attr("disabled","disabled");
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var storageNo = $(e).attr('storageNo');
	var url = DOMAIN + '/v1/storageInfo' + isLogin + '&storageNo=' + storageNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
/* 	var allmoney = 0;
	$.ajax({
	    type: "GET",
	    url:   DOMAIN + '/v1/storageInfo' + isLogin + '&storageNo=' + storageNo,
	    cache: false,
	    async: false,
	    success: function (result) {
	        var datalist = result.data;
			for (var i = 0;i<datalist.length;i++) {
				allmoney += datalist[i].money; 
				console.log(datalist);
			}
			
	    },
	});
	allmoney = allmoney.toFixed(2);
	allmoney = allmoney.toString();
	document.getElementById("moneynum").innerHTML=allmoney;
	
	saleNo = null; */
}

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function () {
	//getSelList($("#purchaseType1"), "/v1/purchaseType" + isLogin);
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions',
		{
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);
	
	var storage_type1 = $("#storageType option:checked").html();
	if(storage_type1=="采购入库"){
			$("#refundOption").css("display","none");
			$("#purOption").css("display","block");
			$("#stor_customer").html("供应商");
			
	}else{
			$("#refundOption").css("display","block");
			$("#purOption").css("display","none");
			$("#stor_customer").html("退货客户");
	}

})

//关闭
$("#AddPur-closeBtn").click(function () {
	$("#close-btn")[0].click();
})

function selectRefund(row){
	$("#refundCode").val(row.refundCode);
	$("#customerName").val(row.customerName);
	
	var url = DOMAIN + '/v1/refundInfo' + isLogin + '&refundCode=' + row.refundCode;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: {}
		}
	);

}

function selectProduct(row){
	$("#productName").val(row.name);
	$("#productCode").val(row.code);
	$("#productType").val(row.levelOneName + "/" + row.levelTwoName);
	$("#grade").val(row.gradeName);
	$("#units").val(row.units);
}

function selectPurchaseOrder(row){
	$("#purchaseCode").val(row.orderNo);
	$("#customerName").val(row.name);
	
	var url = DOMAIN + '/v1/purchaseOrderInfo' + isLogin + '&orderNo=' + row.orderNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: {}
		}
	);
	var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
/* 	var allmoney = 0;
		$.ajax({
		    type: "GET",
		    url:   DOMAIN + '/v1/purchaseOrderInfo' + isLogin + '&orderNo=' + row.orderNo,
		    cache: false,
		    async: false,
		    success: function (result) {
		        var datalist = result.data;
				for (var i = 0;i<datalist.length;i++) {
					allmoney += datalist[i].money; 
					console.log(datalist);
				}
				
		    },
		});
		allmoney = allmoney.toFixed(2);
		allmoney = allmoney.toString();
		document.getElementById("moneynum").innerHTML=allmoney;
		row.orderNo = null; */
}
